package com.example.springboot.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.example.springboot.controller.dto.LoginDTO;
import com.example.springboot.controller.request.BaseRequest;
import com.example.springboot.controller.request.LoginRequest;
import com.example.springboot.controller.request.PasswordRequest;
import com.example.springboot.entity.Admin;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.mapper.AdminMapper;
import com.example.springboot.service.IAdminService;
import com.example.springboot.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @Author:Domen
 * @Date:2023/11/7 16:34
 */

@Slf4j
@Service
public class AdminService implements IAdminService {

    private final String DEFAULT_PASS = "123";
    private final String PASS_SALT = "dae";



    @Autowired
    AdminMapper adminMapper;

    @Override
    public List<Admin> list() {
        return adminMapper.list();
    }

    @Override
    public PageInfo<Admin> page(BaseRequest baseRequest) {
        PageHelper.startPage(baseRequest.getPageNum(),baseRequest.getPageSize());
        List<Admin> admin = adminMapper.listByCondition(baseRequest);
        PageInfo<Admin> pageInfo = new PageInfo<>(admin);
        return pageInfo;
    }

    @Override
    public void save(Admin admin) {
        if(StrUtil.isBlank(admin.getPassword())){
            admin.setPassword(DEFAULT_PASS);
        }
        admin.setPassword(securePass(admin.getPassword()));  //加密+加盐
        try{
            adminMapper.save(admin);
        } catch (DuplicateKeyException e){
            log.error("数据插入失败,username:{}",admin.getUsername());
            throw new ServiceException("用户名插入失败");
        }
    }

    @Override
    public Admin getById(Integer id) {
        return adminMapper.getById(id);
    }

    @Override
    public void update(Admin admin) {
        admin.setUpdateTime(new Date());
        adminMapper.updateById(admin);
    }

    @Override
    public void deleteById(Integer id) {
        adminMapper.deleteById(id);
    }

    @Override
    public LoginDTO login(LoginRequest request) {
        Admin admin = null;
        try{
            admin = adminMapper.getByUsername(request.getUsername());
        }catch(Exception e){
            log.error("根据用户名{}查询出错",request.getUsername());
            throw new ServiceException("用户名错误");
        }
        if (admin == null) {
            throw new ServiceException("用户名或密码错误", "无token，请重新登录");
        }
        if (!admin.isStatus()) {
            throw new ServiceException("当前用户处于禁用状态，请联系管理员");
        }
        //判断密码是否合法
        String securePass = securePass(request.getPassword());
        if(!securePass.equals(admin.getPassword())){
            throw new ServiceException("用户名或密码错误");
        }
        LoginDTO loginDTO = new LoginDTO();
        BeanUtils.copyProperties(admin,loginDTO);

        //生成token
        String token = TokenUtils.genToken(String.valueOf(admin.getId()), admin.getPassword());
        loginDTO.setToken(token);
        return loginDTO;
    }

    @Override
    public void changePass(PasswordRequest request) {
        //对新密码进行加密
        request.setNewPass(securePass(request.getNewPass()));
        int count = adminMapper.updatePass(request);
        if(count <= 0){
            throw new ServiceException("用户名或密码错误");
        }

    }

    private String securePass(String password){
        return SecureUtil.md5(password + PASS_SALT);
    }


}
